#region Summary

// 
// Owner : JackieHan 
// 
// Solution : Jackie.Utility 
// 
// Project : Jackie.Utility
// 
// File : JQGridRenderer.cs
// 
// CopyRight : Copyright © 2010-2011 Skomart Corporation, All Rights Reserved 
// 
// Summary : 生成JQGrid Html and Javascript
// 
// History : 
//			2010-10-15 13:39:12	    Create 
// 

#endregion

#region Using

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using Jackie.Utility.CustomExtension;

#endregion

namespace Jackie.Utility.JQuery.Grid
{
    /// <summary> 
    /// 生成JQGrid Html and Javascript
    /// </summary>
    public class JQGridRenderer
    {
        /// <summary>
        /// 生成JQGrid的Html和Javascript
        /// </summary>
        /// <param name="grid">Grid</param>
        /// <returns></returns>
        public static HtmlString RenderHtml(JQGrid grid)
        {
            //检测Grid对象Id属性不为空
            if (string.IsNullOrEmpty(grid.Id))
                throw new Exception("You need to set Id for this grid.");
            //生成Html
            StringBuilder jqGridBuilder = new StringBuilder();
            jqGridBuilder.AppendFormat(0, "<table id='{0}_Grid'></table>", grid.Id);
            jqGridBuilder.AppendFormat(0, "<div id='{0}_Grid_Pager'></div>", grid.Id);
            //生成JavaScript
            jqGridBuilder.Append(GetStartUpJavascript(grid));
            return new HtmlString(jqGridBuilder.ToString());
        }

        /// <summary>
        /// 生成Script
        /// </summary>
        /// <param name="grid">Grid</param>
        /// <returns></returns>
        private static string GetStartUpJavascript(JQGrid grid)
        {
            StringBuilder scriptBuilder = new StringBuilder();
            scriptBuilder.Append(0, "<script type='text/javascript'>");
            scriptBuilder.Append(1, "$(document).ready(function(){");
            scriptBuilder.Append(1, GetStartUpOptions(grid));
            scriptBuilder.Append(1, GetComandButtonJavascript(grid));
            scriptBuilder.Append(1, GetLoadErrorHandle());
            if ((grid.ToolBar.ShowToolBar) && (grid.ToolBar.Buttons.Count > 0))
                scriptBuilder.Append(1, GetToolBarButtonJavascript(grid));
            if (grid.ShowSearchToolBar)
                scriptBuilder.Append(1, GetSearchToolBarJavascript(grid));
            scriptBuilder.Append(1, "});");
            scriptBuilder.Append(0, "</script>");
            return scriptBuilder.ToString();
        }

        /// <summary>
        /// 生成创建SearchToolbar的Javascript
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        private static string GetSearchToolBarJavascript(JQGrid grid)
        {
            return string.Format("jQuery('#{0}').jqGrid('filterToolbar');", grid.Id + "_Grid");
        }

        /// <summary>
        /// 生成创建Toolbar的Javascript
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        private static string GetToolBarButtonJavascript(JQGrid grid)
        {
            StringBuilder toolBarButtonBuilder = new StringBuilder();
            toolBarButtonBuilder.AppendFormat("$('#t_{0}_Grid')", grid.Id);
            int i = 1;
            foreach (var button in grid.ToolBar.Buttons)
            {
                string buttonId = string.IsNullOrEmpty(button.Id) ? grid.Id + "_Grid_ToolBar_Button" + i : button.Id;
                string clickEventHandler = string.IsNullOrEmpty(button.ClickEventHandler)
                                               ? "JQGridToolBarButton" + i + "EventHandler"
                                               : button.ClickEventHandler;
                toolBarButtonBuilder.AppendFormat(
                    ".append(\"<input id='{0}' type='button' value='{1}' class='{2}' onclick='{3}()' />\")", buttonId,
                    button.Value, button.Css, clickEventHandler);
                i++;
            }
            toolBarButtonBuilder.Append(";");
            return toolBarButtonBuilder.ToString();
        }

        /// <summary>
        /// 创建LoadData错误的处理方法的Javascript
        /// </summary>
        /// <returns></returns>
        private static string GetLoadErrorHandle()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(2, "function jqGrid_aspnet_loadErrorHandler(xht, st, handler) {");
            builder.Append(3, "jQuery(document.body).css('font-size','100%'); jQuery(document.body).html(xht.responseText);");
            builder.Append(2, "}");
            return builder.ToString();
        }

        /// <summary>
        /// 创建Grid常见命令按钮的显示javascript   add,edit,dellete,search,refresh
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        private static string GetComandButtonJavascript(JQGrid grid)
        {
            StringBuilder comandBarBuilder = new StringBuilder();

            comandBarBuilder.AppendFormat("$('#{0}_Grid').jqGrid(", grid.Id);
            comandBarBuilder.AppendFormat("'navGrid','#{0}_Grid_Pager',{{", grid.Id);
            comandBarBuilder.AppendFormat("{0}", GetCommandButtonOption(grid));
            comandBarBuilder.Append(2, "})");
            return comandBarBuilder.ToString();
        }

        /// <summary>
        /// 生成命令按钮选项的Javascript
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        private static string GetCommandButtonOption(JQGrid grid)
        {
            StringBuilder comandBarOptionBuilder = new StringBuilder();

            comandBarOptionBuilder.AppendFormat("add:{0},", grid.CommonButton.Add.ToString().ToLower());
            comandBarOptionBuilder.AppendFormat("edit:{0},", grid.CommonButton.Eidt.ToString().ToLower());
            comandBarOptionBuilder.AppendFormat("del:{0},", grid.CommonButton.Delete.ToString().ToLower());
            comandBarOptionBuilder.AppendFormat("search:{0},", grid.CommonButton.Search.ToString().ToLower());
            comandBarOptionBuilder.AppendFormat("refresh:{0}", grid.CommonButton.Refresh.ToString().ToLower());

            return comandBarOptionBuilder.ToString();
        }

        /// <summary>
        /// 生成JQGrid属性
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        private static string GetStartUpOptions(JQGrid grid)
        {
            string gridJs = string.Format("$('#{0}_Grid')", grid.Id);

            StringBuilder optionBuilder = new StringBuilder();
            optionBuilder.AppendFormat(2, "{0}.jqGrid({{", gridJs);
            optionBuilder.AppendFormat(3, "url:'{0}',", grid.DataUrl);
            optionBuilder.AppendFormat(3, "datatype:'{0}',", grid.DataType.ToString().ToLower());
            optionBuilder.AppendFormat(3, "mtype:'{0}',", "GET");
            optionBuilder.AppendFormat(3, "colNames:[{0}],", GetColumnHeaders(grid));
            optionBuilder.AppendFormat(3, "colModel:[{0}],", GetColumnModels(grid));
            optionBuilder.AppendFormat(3, "rowNum:{0},", grid.RowNum);
            optionBuilder.AppendFormat(3, "rowList:[{0}],", GetRowList(grid));
            optionBuilder.AppendFormat(3, "pager:'#{0}_Grid_Pager',", grid.Id);
            optionBuilder.AppendFormat(3, "viewrecords:{0},", grid.ViewRecords.ToString().ToLower());
            optionBuilder.AppendFormat(3, "sortname:'{0}',", grid.DefaultSortField);
            optionBuilder.AppendFormat(3, "sortorder:'{0}',", grid.DefaultSortType.ToString().ToLower());
            optionBuilder.AppendFormat(3, "height:{0},", grid.Height);
            if (grid.AutoWidth)
                optionBuilder.AppendFormat(3, "autowidth:{0},", "true");
            else
                optionBuilder.AppendFormat(3, "width:{0},", grid.Width);
            optionBuilder.AppendFormat(3, "multiselect:{0},", grid.Multiselect.ToString().ToLower());
            optionBuilder.AppendFormat(3, "loadError:{0},", "jqGrid_aspnet_loadErrorHandler");
            if (grid.ToolBar.ShowToolBar)
                optionBuilder.AppendFormat(3, "toolbar:[{0}],", GetToolBarOption(grid));
            optionBuilder.AppendFormat(3, "caption:'{0}'", grid.Caption);
            optionBuilder.Append(2, "});");
            return optionBuilder.ToString();
        }

        /// <summary>
        /// 创建Toolbar的选项参数
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        private static string GetToolBarOption(JQGrid grid)
        {
            StringBuilder toolBarBuilder = new StringBuilder();
            toolBarBuilder.AppendFormat("{0},'{1}'", grid.ToolBar.ShowToolBar.ToString().ToLower(),
                                        grid.ToolBar.Position.ToString().ToLower());
            return toolBarBuilder.ToString();
        }

        /// <summary>
        /// 获取列的定义
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        private static string GetColumnModels(JQGrid grid)
        {
            StringBuilder columnModelsBuilder = new StringBuilder();
            grid.Columns.ForEach(item => columnModelsBuilder.AppendFormat(4, "{{{0}}},", GetColumnModel(item)));
            return "\n" + columnModelsBuilder.ToString().Substring(0, columnModelsBuilder.ToString().Length - 2);
        }

        /// <summary>
        /// 获取某一列的定义
        /// </summary>
        /// <param name="column"></param>
        /// <returns></returns>
        private static string GetColumnModel(JQGridColumn column)
        {
            StringBuilder columnModelBuilder = new StringBuilder();
            if (string.IsNullOrEmpty(column.DataField))
            {
                throw new Exception("You should set DataField Property!");
            }
            //name
            columnModelBuilder.AppendFormat("name:'{0}',", column.DataField);
            //sortable   index
            if (column.Sortable == false)
                columnModelBuilder.AppendFormat("sortable:{0},", column.Sortable.ToString().ToLower());
            else
                columnModelBuilder.AppendFormat("index:'{0}',",
                                         string.IsNullOrEmpty(column.IndexField) ? column.DataField : column.IndexField);
            //width
            columnModelBuilder.AppendFormat("width:{0},", column.Width);
            //align
            columnModelBuilder.AppendFormat("align:'{0}',", column.Align.ToString().ToLower());
            //hidden
            if (!column.Visible)
                columnModelBuilder.AppendFormat("hidden:{0},", "true");
            //searchable
            if (!column.Searchable)
                columnModelBuilder.AppendFormat("search:{0},", "false");
            //formatter
            if (column.Formatter != ColumnTextFormatter.Normal)
                columnModelBuilder.AppendFormat("formatter", GetFormatter(column.Formatter));
            //stype   //searchoptions{value:}
            if ((column.SearchElementType == SearchElementType.DropDown)
                && (column.SearchOptions.SelectOptionValue.Count != 0))
            {
                columnModelBuilder.AppendFormat("stype:\"{0}\",", "select");
                var selectOptionBuilder = new StringBuilder();
                foreach (var key in column.SearchOptions.SelectOptionValue.Keys)
                {
                    selectOptionBuilder.AppendFormat(
                        string.IsNullOrEmpty(selectOptionBuilder.ToString()) ? "{0}:{1}" : ";{0}:{1}", key,
                        column.SearchOptions.SelectOptionValue[key]);
                }
                columnModelBuilder.AppendFormat("searchoptions: {{ value: \"{0}\"}},", selectOptionBuilder.ToString());
            }
            return columnModelBuilder.ToString().Substring(0, columnModelBuilder.ToString().Length - 1);
        }

        private static string GetFormatter(ColumnTextFormatter columnTextFormatter)
        {
            var formatter = string.Empty;
            switch (columnTextFormatter)
            {
                case ColumnTextFormatter.CheckBox:
                    formatter = "checkbox";
                    break;
                case ColumnTextFormatter.Link:
                    formatter = "link";
                    break;
                case ColumnTextFormatter.Integer:
                    formatter = "integer";
                    break;
                case ColumnTextFormatter.Date:
                    formatter = "date";
                    break;
                case ColumnTextFormatter.Currency:
                    formatter = "currency";
                    break;
                default:
                    throw new Exception("not support formatter");
            }
            return formatter;
        }

        /// <summary>
        /// 获取列头
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        private static string GetColumnHeaders(JQGrid grid)
        {
            string headers = string.Empty;
            grid.Columns.ForEach(item =>
                                     {
                                         var columnHeaderText = string.IsNullOrEmpty(item.HeaderText) ? item.DataField : item.HeaderText;
                                         headers += string.Format("'{0}',", columnHeaderText);
                                     });
            return string.IsNullOrEmpty(headers) ? string.Empty : headers.Substring(0, headers.Length - 1);
        }

        /// <summary>
        /// 或页行选择数据
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        private static string GetRowList(JQGrid grid)
        {
            string rowList = string.Empty;
            grid.RowList.ForEach(item => { rowList += item + ","; });
            return string.IsNullOrEmpty(rowList) ? string.Empty : rowList.Substring(0, rowList.Length - 1);
        }

    }
}